<?php

namespace app\admin\model\tongcheng;

use addons\tongcheng\library\WebSocketService;
use think\Model;
use traits\model\SoftDelete;

class RiderModel extends Model
{

    use SoftDelete;


    // 表名
    protected $name = 'tongcheng_rider';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'integer';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = 'deletetime';

    // 追加属性
    protected $append = [
        'gender_text',
        'work_status_text',
        'work_type_text',
        'status_text'
    ];

    protected static function init()
    {
        self::afterInsert(function ($row) {
            // $user = $row->user;
            // if ($user) {
            //     $user->rider_id = $row->id;
            //     $user->save();
            // }

            // 创建骑手余额账户（不同区域同一账户）
            $rider_balance = RiderBalanceModel::get([
                // 'zone_id'  => $row['zone_id'],
                // 'rider_id' => $row['id'],
                'user_id' => $row['user_id'],
            ]);
            if (!$rider_balance) {
                RiderBalanceModel::create([
                    'zone_id'        => $row['zone_id'],
                    'user_id'        => $row['user_id'],
                    // 'rider_id'       => $row['id'],
                    'balance'        => 0,
                    'total_inc'      => 0,
                    'total_dec'      => 0,
                    'total_withdraw' => 0,
                ]);
            }
        });
    }


    public function getGenderList()
    {
        return ['1' => __('Gender 1'), '0' => __('Gender 0')];
    }

    public function getWorkStatusList()
    {
        return ['1' => __('Work_status 1'), '0' => __('Work_status 0')];
    }

    public function getWorkTypeList()
    {
        return ['full' => __('Work_type full'), 'part' => __('Work_type part')];
    }

    public function getStatusList()
    {
        return ['1' => __('Status 1'), '0' => __('Status 0')];
    }


    public function getGenderTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['gender']) ? $data['gender'] : '');
        $list  = $this->getGenderList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getWorkStatusTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['work_status']) ? $data['work_status'] : '');
        $list  = $this->getWorkStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getWorkTypeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['work_type']) ? $data['work_type'] : '');
        $list  = $this->getWorkTypeList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getStatusTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['status']) ? $data['status'] : '');
        $list  = $this->getStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function user()
    {
        return $this->belongsTo('app\admin\model\User', 'user_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }


    public function zone()
    {
        return $this->belongsTo('Zone', 'zone_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }

    /**
     * 获取骑手信息
     * @param self|int $rider_id 骑手模型或者骑手id
     * @return array|bool|\PDOStatement|string|Model|null
     */
    public static function getById($rider_id, $regain = false)
    {
        if (is_numeric($rider_id)) {
            return RiderModel::get(['user_id' => $rider_id]);
        } else if (in_array(get_class($rider_id), [RiderModel::class, \addons\tongcheng\model\RiderModel::class])) {
            if ($regain) {
                return self::get(['user_id' => $rider_id]);
            }
            return $rider_id;
        }

        throw new \Exception('rider_id格式错误');
    }

    /**
     * 根据用户ID获取骑手姓名
     * @param $user_id
     * @return float|mixed|string
     */
    public static function getRealName($user_id)
    {
        return self::where('user_id', $user_id)->value('real_name');
    }

    /**
     * 获取在线骑手
     * @param $zone_id
     * @return array|bool|\PDOStatement|string|\think\Collection
     */
    public static function getOnlineRiders($zone_id = 0)
    {
        if ($zone_id) {
            $user_ids = WebSocketService::getOnlineRiderIdsByZoneId($zone_id);
        } else {
            $user_ids = WebSocketService::getAllOnlineRider();
        }

        if (!$user_ids) {
            return [];
        }

        return self::where('status', '1')
            ->where('work_status', '1')
            ->whereIn('user_id', $user_ids)
            ->field('id, user_id, real_name, lng, lat')
            ->select();
    }

    /**
     * 获取在线司机数量
     * @param $zone_id
     * @return array|bool|\PDOStatement|string|\think\Collection
     */
    public static function getOnlineRiderCount($zone_id = 0)
    {   
        return 0;
        if ($zone_id) {
            $user_ids = WebSocketService::getOnlineRiderIdsByZoneId($zone_id);
        } else {
            $user_ids = WebSocketService::getAllOnlineRider();
        }
        
        if (!$user_ids) {
            return 0;
        }

        return count($user_ids);
    }
}
